import { Request, Response } from "express";
import UserModel from "../../schema/user";
import RoleModel from "../../schema/role";
import { getToken } from "../../utils/jwt";

// Mongoose 类的实例
import MongooseController from "../mongoose/mongoose";
const UserModelIns = new MongooseController(UserModel);
const RoleModelIns = new MongooseController(RoleModel);

// response 响应类型类的实例
import ResController from "../res/res";
const ResIns = new ResController();

import axios from 'axios';

class System {
  constructor() {}

  async login(req: Request, res: Response) {
    try {
      const { account, password } = req.body || {};
      const users = await UserModelIns.Find({ account, password });
      if (!users.length) {
        ResIns.isNotExist(res);
      } else {
        const user = users[0];

        // 加密对象
        const payload = JSON.parse(JSON.stringify(user));

        // 获取 token
        const token = await getToken(payload);

        const role = await RoleModelIns.Find({ roleId: user.roleId })

        let auths = {}
        if (role.length) {
          const { permissionKey, halfPermissionKey, permissionButtonKeys, roleId } = role[0]
          auths = {
            permissionKey,
            halfPermissionKey,
            permissionButtonKeys,
          }
        }

        // 将 token 设置为 cookie
        res.cookie("token", token, {
          // httpOnly: true,
          maxAge: 1000 * 60 * 60 * 24, // 1 天过期
        });

        ResIns.Success(res, { ...payload, token, auths });
      }
    } catch (err) {
      console.log(err)
      ResIns.Database(res, err);
    }
  }
}

export default System;
